package com.example.barcodeapp.ui;

import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.barcodeapp.MainActivity;
import com.example.barcodeapp.R;
import com.example.barcodeapp.base.BaseActivity;
import com.example.barcodeapp.bean.YanZhengMaBean;
import com.example.barcodeapp.interfaces.IBasePersenter;
import com.example.barcodeapp.ui.wode.activity.UpDatePhoneNamberActivity;
import com.example.barcodeapp.utils.DisplayUtil;
import com.example.barcodeapp.utils.Show;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.Instant;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity {


    protected Resources res;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.tv_regist)
    TextView tvRegist;
    @BindView(R.id.login_et_phonenum)
    EditText loginEtPhonenum;
    @BindView(R.id.login_ET_password)
    EditText loginETPassword;
    @BindView(R.id.login_et_yanzhengma)
    EditText loginEtYanzhengma;
    @BindView(R.id.login_TV_getYanzhengma)
    TextView loginTVGetYanzhengma;
    @BindView(R.id.layout_login_by_yan)
    LinearLayout layoutLoginByYan;
    @BindView(R.id.tv_to_find_password)
    TextView tvToFindPassword;
    @BindView(R.id.login_BT_toLogin)
    TextView loginBTToLogin;
    @BindView(R.id.tv_login_message)
    TextView tvLoginMessage;
    @BindView(R.id.regist_et_phonenum)
    EditText registEtPhonenum;
    @BindView(R.id.regist_et_yanzhengma)
    EditText registEtYanzhengma;
    @BindView(R.id.regist_TV_getYanzhengma)
    TextView registTVGetYanzhengma;
    @BindView(R.id.regist_BT_toRegist)
    TextView registBTToRegist;
    @BindView(R.id.tv_regist_message)
    TextView tvRegistMessage;
    @BindView(R.id.iv_login_by_wx)
    ImageView ivLoginByWx;
    private View layoutLogin, layoutRegist;
    private String yanzhengma;

    private CountDownTimer start = null;

    @Override
    protected int getLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        layoutLogin = findViewById(R.id.layout_login);
        layoutRegist = findViewById(R.id.layout_regist);
        tvLogin = findViewById(R.id.tv_login);//密码登录
        tvRegist = findViewById(R.id.tv_regist);//验证码登录
        loginEtPhonenum = findViewById(R.id.login_et_phonenum);//手机号
        loginETPassword = findViewById(R.id.login_ET_password);//密码
        layoutLoginByYan = findViewById(R.id.layout_login_by_yan);
        loginEtYanzhengma = findViewById(R.id.login_et_yanzhengma);
        loginTVGetYanzhengma = findViewById(R.id.login_TV_getYanzhengma);
        tvToFindPassword = findViewById(R.id.tv_to_find_password);//忘记密码
        loginBTToLogin = findViewById(R.id.login_BT_toLogin);//立刻登录
        tvLoginMessage = findViewById(R.id.tv_login_message);//用户协议
        registEtPhonenum = findViewById(R.id.regist_et_phonenum);//验证码电话
        registEtYanzhengma = findViewById(R.id.regist_et_yanzhengma);//验证码框
        registTVGetYanzhengma = findViewById(R.id.regist_TV_getYanzhengma);//获取验证码
        registBTToRegist = findViewById(R.id.regist_BT_toRegist);//验证码立即登录
        tvRegistMessage = findViewById(R.id.tv_regist_message);//用户协议
        ivLoginByWx = findViewById(R.id.iv_login_by_wx);//三方微信登录
    }

    @Override
    protected IBasePersenter initPersenter() {
        return null;
    }

    @Override
    protected void initData() {

    }


    @OnClick({R.id.tv_login_message, R.id.regist_TV_getYanzhengma, R.id.tv_regist_message, R.id.iv_login_by_wx,R.id.login_BT_toLogin,R.id.regist_BT_toRegist,R.id.tv_to_find_password,R.id.tv_regist,R.id.tv_login})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_login_message://用户协议

                startActivity(new Intent(LoginActivity.this, YongHuXieYiActivity.class));


                break;
            case R.id.regist_TV_getYanzhengma://获取验证码按钮


                String text = registEtPhonenum.getText().toString();
                boolean mobileNO2 = isMobileNO(text);

                if (start == null) {
                    if (mobileNO2) {
                        Http(text);
                        start = new CountDownTimer(60 * 1000, 1000) {
                            @Override
                            public void onTick(long millisUntilFinished) {
                                registTVGetYanzhengma.setText("S " + millisUntilFinished / 1000);
                                registTVGetYanzhengma.setBackgroundResource(R.drawable.shape_send_verification_code1);
                            }
                            @Override
                            public void onFinish() {
                                registTVGetYanzhengma.setText("重新获取验证码");
                                registTVGetYanzhengma.setTextSize(15);
                                start.cancel();
                                start = null;
                            }
                        }.start();
                    } else {
                        Toast.makeText(LoginActivity.this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
                    }
                }










                break;
            case R.id.tv_regist_message://注册协议
                break;
            case R.id.iv_login_by_wx://微信登录图标
                break;
            case R.id.login_BT_toLogin://密码登录按钮
//                if (loginEtPhonenum.getText().toString().isEmpty()){
//                    boolean mobileNO = isMobileNO(loginEtPhonenum.getText().toString());
//                    if (mobileNO){
//                        if (loginEtPhonenum.getText().toString().isEmpty()){
//                            Intent instant = new Intent(LoginActivity.this, MainActivity.class);
//                            startActivity(instant);
//                        }else {
//                            Show.showMessage("请输入密码");
//                            return;
//                        }
//                    }else {
//                        Show.showMessage("请输入正确的电话号码");
//                        return;
//                    }
//
//                }else {
//                    Show.showMessage("请输入电话号码");
//                    return;
//                }
                Intent instant = new Intent(LoginActivity.this, MainActivity.class);
                           startActivity(instant);
                break;
            case R.id.regist_BT_toRegist://验证码登录按钮
                if (!registEtPhonenum.getText().toString().isEmpty()){
                    boolean mobileNO = isMobileNO(registEtPhonenum.getText().toString());
                    if (mobileNO){
                       if (!registEtYanzhengma.getText().toString().isEmpty()){
                           Log.e("SAdawadsadw", "onClick: "+ yanzhengma);
                           if (registEtYanzhengma.getText().toString().equals(yanzhengma)){
                               Show.showMessage("登陆成功");
                               startActivity(new Intent(LoginActivity.this, MainActivity.class));
                           }else {
                               Show.showMessage("验证码不正确");
                               return;
                           }
                       }else {
                           Show.showMessage("请输入验证码");
                           return;
                       }
                    }else {
                        Show.showMessage("请输入正确的电话号码");
                        return;
                    }
                }else {
                    Show.showMessage("请输入电话号码");
                    return;
                }
                break;
            case R.id.tv_to_find_password://忘记密码

                break;
            case R.id.tv_regist://验证码
                showRegistPage();

                break;
            case R.id.tv_login://密码
                showLoginPage();
                break;


        }
    }

    private void Http(String text) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL("http://new.jifengyinyue.com/api/user/code?"+"phone="+text);
                    Log.e("dawdasdawdasd", "run: "+url );
                    Log.e("dawdasdawdasd", "run: "+url );
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    int responseCode = urlConnection.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        InputStream inputStream = urlConnection.getInputStream();
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                        String line = null;
                        StringBuffer stringBuffer = new StringBuffer();
                        while ((line = bufferedReader.readLine()) != null) {
                            stringBuffer.append(line);
                        }
                        String json = stringBuffer.toString();
                        final Gson gson = new Gson();
                        final YanZhengMaBean fengzhuanglei = gson.fromJson(json, YanZhengMaBean.class);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
yanzhengma=fengzhuanglei.getCode()+"";
                            }
                        });

                    }

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void showLoginPage(){
        tvRegist.setSelected(false);
        tvLogin.setSelected(true);
        tvLogin.setTextSize(DisplayUtil.sp2px(this,8));
        tvRegist.setTextSize(DisplayUtil.sp2px(this,5));
        layoutLogin.setVisibility(View.VISIBLE);
        layoutRegist.setVisibility(View.GONE);
    }
    private void showRegistPage(){
        tvRegist.setSelected(true);
        tvLogin.setSelected(false);
        tvRegist.setTextSize(DisplayUtil.sp2px(this,8));
        tvLogin.setTextSize(DisplayUtil.sp2px(this,5));
        layoutLogin.setVisibility(View.GONE);
        layoutRegist.setVisibility(View.VISIBLE);
    }
    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {
/*
移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
联通：130、131、132、152、155、156、185、186
电信：133、153、180、189、（1349卫通）
总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
*/
        String telRegex = "[1][3578]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (mobiles == null || mobiles.length() == 0 || mobiles.length() != 11)
            return false;
        else
            return mobiles.matches(telRegex);

    }
}